/**
 * PaymentController
 *
 * @description :: Server-side logic for managing payments
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */
var moment = require('moment');
var request = require('request');
var wechat = require('./wechat');
var crypto = require('crypto');
var royal = require('./RoyalPay');
var fs = require('fs');
var wms = require('./WmsApi');
var oss = require('./AliOss');
const co = require('co');
const cheerio = require('cheerio');
const https = require('https');
module.exports = {

  addOrder: function (req, res) {
    var reqbody = {
      product: JSON.stringify(req.body.product),
      userId: req.session.openId,
      createTime: moment().unix(),
    };
    Payment.create(reqbody).then(function (record) {
      console.log(record);
      res.send({orderId: record.id});
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  paymentMethod: function (req, res) {
    var orderId = req.params.orderId;
    Payment.find({id: orderId}).then(function (result) {
      var products = JSON.parse(result[0].product);
      res.view('paymentMethod', {product: products});
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  //generate signature
  getSig: function (req, res) {
    var noncestr = 'abqe1231231209ioaois';
    var timestamp = moment().unix();
    var url = req.body.url;
    wechat.getJsTicket(function (ticket) {
      var str = 'jsapi_ticket='+ticket+'&noncestr='+noncestr+'&timestamp='+timestamp+'&url='+url;
      console.log('string to cipher is:',str);
      var sha1 = crypto.createHash('sha1');
      sha1.update(str);
      var sig = sha1.digest('hex');
      var json = {
        timestamp: timestamp,
        noncestr: noncestr,
        signature: sig
      };
      res.send(json);
    })
  },

  royalpay: function (req, res) {
    royal.create_jsapi_order(req.body.order_id, req.body.order_title, req.body.price, 'AUD', req.body.openid, function (call) {
      console.log(call);
      if (call.return_code == 'SUCCESS') {
        royal.create_payment_uri(call.pay_url, function (call) {
          res.send({status: 'success', pay_uri: call})
        })
      }
    })
  },

  callback: function (req, res) {
    var order_id = req.param('order_id');
    var payment = Number(req.body.real_fee)/100;
    var paymethod = 'wechat';
    var json = req.body;
    wms.upload_payment_info(order_id, payment, paymethod, json, function (call) {
      console.log(call);
    })
    res.ok();
  },

  getEx: function (req, res) {
    royal.get_current_ex(function (call) {
      res.send(call);
    })
  },

  transfer: function (req, res) {
    var order_id = req.params.id;
    wms.getOrderDetail(order_id, function (call) {
      console.log('order details:', call);
      var inv_no = JSON.parse(call)[0].sn;
      var payment = JSON.parse(call)[0].total_amount;
      var order_id = JSON.parse(call)[0].id
      res.view('transfer', {inv_no: inv_no, payment: payment, order_id: order_id});
    })
  },

  downloadMedia: function (req, res) {
    var media_id = req.param('media_id');
    var order_id = req.param('order_id');
    var payment = req.param('payment');
    // wechat.getAccessToken(function (call) {
    //   var download_media_url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token='+call+'&media_id='+media_id;
    //   request.head(download_media_url, function (err, resp, body) {
    //     if (err) return err;
    //     request(download_media_url).pipe(fs.createWriteStream('http://auewe.oss-ap-southeast-2.aliyuncs.com/transfer_snap/'+order_id+'.jpg'));
    //     var img_uri = 'http://auewe.oss-ap-southeast-2.aliyuncs.com/transfer_snap/'+order_id+'.jpg';
    //     wms.upload_payment_info(order_id, [img_uri], function (call) {
    //       res.ok('success');
    //     })
    //   })
    // })
    // oss.download_meadia(media_id, order_id, function (callback) {
    //   console.log(callback);
    //   res.ok('success');
    // })
    oss.download_meadia(media_id, order_id, function (call) {
      console.log(call);
      var json = ['http://auewe.oss-ap-southeast-2.aliyuncs.com/transfer_snap/'+order_id+'.jpeg'];
      wms.upload_payment_info(order_id, payment, 'transfer', json, function (call) {
        console.log(call);
      })
    })
    res.ok('success');
  },

  orderStatus: function (req, res) {
    var form = req.body;
    var order_id = form.id;
    wms.getOrderDetail(order_id, function (detail) {
      console.log('order status changed:', detail);
      //socket.io
    })
    res.ok('roger that');
  },

  orderShipping: function (req, res) {
    var order_id = req.params.id;
    res.view('order_shipping', {id: order_id});
  },

  getOrderShipping: function (req, res) {
    var order_id = req.params.id;
    var shipping_co = 'ewe';
    var uri = 'https://m.kuaidi100.com/query?type='+shipping_co+'&postid='+order_id;
    request(uri, function (err, resp, body) {
      var data = JSON.parse(body).data;
      res.send(data);
    })
  }
};

